package com.study.sync;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

public class TestSynchronized {
	public void test1() {
		synchronized (this)  //同步代码块的方式进行同步
		{
			int i = 5;
			while (i-- > 0) {
				System.out.println(Thread.currentThread().getName() + " : " + i);
				try {
					Thread.sleep(500);
				} catch (InterruptedException ie) {
				}
			}
		}
	}

	public synchronized void test2() { //修饰方法的方式进行同步
		int i = 5;
		while (i-- > 0) {
			System.out.println(Thread.currentThread().getName() + " : " + i);
			try {
				Thread.sleep(500);
			} catch (InterruptedException ie) {
			}
		}
	}

	public static void main(String[] args) {
		final TestSynchronized myt2 = new TestSynchronized();
		Thread test1 = new Thread(new Runnable() {
			public void run() {
				myt2.test1();
			}
		}, "test1");
		Thread test2 = new Thread(new Runnable() {
			public void run() {
				myt2.test2();
			}
		}, "test2");
		test1.start();
		test2.start();
		//两个同步代码所需要获得的对象锁都是同一个对象锁，下面main方法时分别开启两个线程，分别调用test1和test2方法，
		//那么两个线程都需要获得该对象锁，另一个线程必须等待。
		new CountDownLatch(0);
		new ReentrantLock();
//		new Semaphore();
//		new CyclicBarrier();
//		new LockSupport();
	}
}
